package com.sgb.kjwl.view.ui.fragment.transport;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppFragNormalMyOfferPageBinding;
import com.sgb.kjwl.model.entity.OrderEntity;
import com.sgb.kjwl.model.entity.self.MyOfferEntity2;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.self.carMaster.MyOfferDetailsActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayGeneralQuotationForCompanyActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayGeneralQuotationOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderActivity;
import com.sgb.kjwl.view.ui.activity.transport.PayQuotationOrderForCompanyActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.self.carMasters.NormalMyOfferAdapter;
import com.sgb.kjwl.viewmodel.transport.NormalMyOfferPageViewModel;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.common.base.BaseFragment;
import com.swgk.core.util.UserOperating;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2021/9/22 11:58
 * @Description: 普通货源-我的报价列表页
 *
 */
public class NormalMyOfferPageFragment extends BaseFragment<NormalMyOfferPageViewModel, AppFragNormalMyOfferPageBinding> {
    //页面状态:0全部  1已报价  2待支付  3已支付 5已失效
    private int mStatus;
    private List<MyOfferEntity2> mList;
    private NormalMyOfferAdapter mAdapter;

    @Override
    protected int layoutId() {
        return R.layout.app_frag_normal_my_offer_page;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(NormalMyOfferPageViewModel.class);
    }

    public static NormalMyOfferPageFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, type);
        NormalMyOfferPageFragment fragment = new NormalMyOfferPageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void init() {
        initPage();
        initViews();
        initEvent();
    }

    private void initPage() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            // 1已报价  2待支付  3已支付 5已失效
            int status = getArguments().getInt(RouterKey.TYPE, 0);
            switch (status) {
                case 0://全部
                case 1://已报价
                case 2://待支付
                case 3://已支付
                    mStatus = status;
                    break;
                case 4://已失效
                    mStatus = 5;
                    break;
            }
        }
    }

    private void initViews() {
        mList = new ArrayList<>();
        mAdapter = new NormalMyOfferAdapter(mList);
        mBinding.rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        DividerDecoration.builder(_mActivity)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(mBinding.rvList);
        mAdapter.bindToRecyclerView(mBinding.rvList);
        mBinding.rvList.setAdapter(mAdapter);
    }

    @SuppressLint("FragmentLiveDataObserve")
    private void initEvent() {
        mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        mBinding.srlRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mViewModel.getMyOfferOrder(_mActivity, mStatus, false);
                mBinding.srlRefresh.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mViewModel.getMyOfferOrder(_mActivity, mStatus, true);
                mBinding.srlRefresh.finishRefresh();
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            MyOfferEntity2 entity = mList.get(position);
            itemClick(view, entity);
        });
        mViewModel.ldRecord.observe(this, this::showList);
    }

    @SuppressLint("NonConstantResourceId")
    private void itemClick(View view, MyOfferEntity2 entity) {
        switch (view.getId()) {
            case R.id.fl_item:
                MyOfferDetailsActivity.start(_mActivity, entity.getGoodsOfferNo(), true);
                break;
            case R.id.tv_update_offer:
                updateOffer(entity);
                break;
            case R.id.tv_pay_msg_fee:
                //支付信息费
                toPayMsgFee(entity);
                break;
            case R.id.tv_check_order:
                toOrderDetail(entity.getOrderNo());
                break;
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        mViewModel.getMyOfferOrder(_mActivity, mStatus, true);
    }

    /**
     * 更新报价
     */
    private void updateOffer(MyOfferEntity2 entity) {
        if (!TextUtils.isEmpty(entity.getGoodsSourceNo())) {
            if (UserOperating.getInstance().isPersonal()) {
                PayGeneralQuotationOrderActivity.startForResult(getActivity(), entity.getGoodsSourceNo(), true, true, entity.getFreight());
            } else {
                PayGeneralQuotationForCompanyActivity.startForResult(getActivity(), entity.getGoodsSourceNo(), true, true, entity.getFreight());
            }
        }
    }

    /**
     * 运输订单详情
     */
    private void toOrderDetail(String orderNo) {
        Intent intent = new Intent(getActivity(), TransportOrderDetailOwnerActivity.class);
        intent.putExtra("isGoodsOwner", 0);//这里是车主，传值：0
        intent.putExtra("no", orderNo);//订单编号
        startActivity(intent);
    }

    /**
     * 支付信息费
     */
    private void toPayMsgFee(MyOfferEntity2 entity) {
        //所有状态正常——>前去支付
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setGoodsSourceNo(entity.getGoodsSourceNo());
        orderEntity.setCarNumber(entity.getCarNumber());
        orderEntity.setHeightHurdle(entity.getHeightHurdle());
        orderEntity.setWeight(entity.getWeight());
        orderEntity.setCarLen(entity.getCarLenName());
        orderEntity.setCarType(entity.getCarTypeName());
        orderEntity.setCityName(entity.getCityName());
        orderEntity.setProvinceName(entity.getProvinceName());
        orderEntity.setDistrictName(entity.getDistrictName());
        orderEntity.setDetailAddress(entity.getDetailAddress());
        orderEntity.setCarImage(entity.getCarImage());
        orderEntity.setDriverNo(entity.getDriverNo());
        orderEntity.setCarOfferNo(entity.getCarOfferNo());
        orderEntity.setGoodsOfferNo(entity.getGoodsOfferNo());
        orderEntity.setNote(entity.getNote());
        orderEntity.setDiyField(entity.getDiyField());
        orderEntity.setQuotation(true);
        orderEntity.setAllFreight(entity.getAllFreight());
        orderEntity.setIsDump(entity.getIsDump());
        orderEntity.setInTime(entity.getInTime());
        if (!UserOperating.getInstance().isPersonal()) {
            PayQuotationOrderForCompanyActivity.start(_mActivity, entity.getGoodsOfferNo());
        } else {
            PayQuotationOrderActivity.start(_mActivity, entity.getGoodsOfferNo());
        }
    }

    public void showList(ListResponse<List<MyOfferEntity2>> listResponse) {
        mAdapter.setCancelTimer();
        if (listResponse == null || !listResponse.isLoadSuccess()) return;
        if (listResponse.getCurrentPage() <= 1) {
            mList.clear();
        }
        if (listResponse.getList() != null && listResponse.getList().size() > 0) {
            mList.addAll(listResponse.getList());
        }
        mAdapter.notifyDataSetChanged();
        if (!listResponse.isLastPage()) {
            mBinding.srlRefresh.resetNoMoreData();
        } else {
            mBinding.srlRefresh.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mAdapter.setCancelTimer();
    }
}
